using MediatR;
using RBAC.Domain.MaterialManage;
using RBAC.ErrorCode;
using RBAC.Read.Api.Application.Command.ERP.PurchasingManagement.PurchaseInvoicefolder;
using RBAC.Read.Api.Application.Dto.ERP;
using Microsoft.Extensions.Logging;
using RBAC.Interstructrue.Base;
using AutoMapper;

namespace RBAC.Read.Api.Application.Handler.ERP.PurchasingManagement.PurchaseInvoicefolder
{
    public class GetMaterCommandHandler : IRequestHandler<GetMaterCommands, APIPaging<MaterListDto>>
    {
        private readonly IBaseRepository<Mater> materRepository;
        private readonly ILogger<GetMaterCommandHandler> logger;
        private readonly IMapper mapper;

        public GetMaterCommandHandler(
            IBaseRepository<Mater> materRepository,
            ILogger<GetMaterCommandHandler> logger,
            IMapper mapper)
        {
            this.materRepository = materRepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        public Task<APIPaging<MaterListDto>> Handle(GetMaterCommands request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<MaterListDto>();
            try
            {
                logger.LogInformation("开始获取采购管理-物料分页列表 PageIndex={PageIndex}, PageSize={PageSize}", request.PageIndex, request.PageSize);

                // 仅分页，不做任何条件过滤
                var (data, total) = materRepository.GetPaged(request.PageIndex, request.PageSize);

                var dtoList = data.Select(m => new MaterListDto
                {
                    Id = m.Id,
                    MaterCode = m.MaterCode,
                    MaterName = m.MaterName,
                    ModelSpec = m.ModelSpec,
                    Unit = m.Unit,
                    SupplyMode = m.SupplyMode,
                    Status = m.Status
                }).ToList();

                result.Code = APIEnums.Success;
                result.PageDatas = dtoList;
                result.TotalCount = total;
                result.Msg = "获取物料列表成功";
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取物料分页列表失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取物料列表失败";
                result.PageDatas = new List<MaterListDto>();
                result.TotalCount = 0;
            }

            return Task.FromResult(result);
        }
    }
}
